using System;
using System.Collections.Generic;
using System.Linq;

namespace SafeShrink
{
    public static class BatchExtensions
    {
        /// <summary>
        /// 将集合分批处理
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="source">源集合</param>
        /// <param name="size">每批大小</param>
        /// <returns>分批后的集合</returns>
        public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size)
        {
            if (size <= 0)
                throw new ArgumentOutOfRangeException(nameof(size), "批大小必须大于0");

            using var enumerator = source.GetEnumerator();
            while (enumerator.MoveNext())
            {
                yield return GetBatch(enumerator, size);
            }
        }

        private static IEnumerable<T> GetBatch<T>(IEnumerator<T> enumerator, int size)
        {
            do
            {
                yield return enumerator.Current;
            }
            while (--size > 0 && enumerator.MoveNext());
        }
    }
}